package com.woniu.mall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.woniu.common.entity.Result;
import com.woniu.mall.constant.OrderConstants;
import com.woniu.mall.feign.OrderFeignClient;
import com.woniu.mall.pojo.MallOrder;
import com.woniu.mall.pojo.MallPaymentInfo;
import com.woniu.mall.service.IMallPaymentInfoService;
import com.woniu.pay.constant.AliPayInfoConstants;
import com.woniu.user.feignClient.UserFeignClient;
import com.woniu.user.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 坤
 * @since 2023-05-22
 */
@Controller
@RequestMapping("/mallPaymentInfo")
@Api(tags = "支付信息管理")
@Slf4j
public class MallPaymentInfoController {
    @Autowired
    private IMallPaymentInfoService paymentInfoService;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;


    @ApiOperation("商城支付同步回调")
    @RequestMapping(value = "/returnUrl")
    public String returnUrl(){
        log.debug("支付宝同步回调回来了");
        return "redirect:https://c22265g319.yicp.fun/index.html";
    }

    @SneakyThrows
    @ApiOperation("商城支付异步回调")
    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.debug("支付宝异步回调的参数为：{}", params);

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayInfoConstants.ALIPAY_PUBLIC_KEY, AliPayInfoConstants.CHARSET, AliPayInfoConstants.SIGN_TYPE); //调用SDK验证签名
        if(!signVerified){
            return "failure";
        }
        //验签成功
//        1. 获取订单，修改订单信息
        Object order = orderFeignClient.getOrderById(params.get("out_trade_no")).getData();
        String jsonObject = JSON.toJSONString(order);
        MallOrder mallOrder = JSONObject.parseObject(jsonObject, MallOrder.class);
        Integer orderId = Integer.parseInt(params.get("out_trade_no"));
        mallOrder.setOrderId(orderId);
        mallOrder.setOrderStatus(OrderConstants.ORDER_STATUS_FINISH);
        mallOrder.setPaymentTime(new Date());
        orderFeignClient.updateOrder(mallOrder);




//        充值比特币业务
        if (params.get("subject").equals(OrderConstants.RECHARGE_BIT_COIN)){
            String mobile = userFeignClient.getUser(mallOrder.getUserId()).getData().getMobile();
            userFeignClient.addAmount(mobile, new BigDecimal(params.get("total_amount")));
        }

        //2. 添加支付信息到数据库中
        MallPaymentInfo paymentInfo = new MallPaymentInfo();
        paymentInfo.setOrderId(params.get("out_trade_no"));
        paymentInfo.setTransactionId(params.get("trade_no"));
        paymentInfo.setPaymentTotalAmount(new BigDecimal(params.get("total_amount")));
        paymentInfo.setTradeStatus(params.get("trade_status"));
        paymentInfo.setContent(params.toString());
        int result = paymentInfoService.addPaymentInfo(paymentInfo);
        String info = result > 0 ?  "成功" : "失败";
        log.debug("支付信息数据保存" +info);

        return "success";

    }
}
